package com.yin.waimai.controller;

import com.yin.waimai.dto.AddressDTO;
import com.yin.waimai.dto.OrderDTO;
import com.yin.waimai.model.Address;
import com.yin.waimai.model.Order;
import com.yin.waimai.repository.OrderRepository;
import com.yin.waimai.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/orders")
public class UserOrderController {

    private static final Logger log = LoggerFactory.getLogger(UserOrderController.class);

    private final OrderRepository orderRepository;
    private final OrderService orderService;

    @Autowired
    public UserOrderController(OrderRepository orderRepository, OrderService orderService) {
        this.orderRepository = orderRepository;
        this.orderService = orderService;
    }

    /**
     * 获取当前登录用户的订单列表
     * 通过创建者用户名字段查询订单
     */
    @GetMapping("/user")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<OrderDTO>> getUserOrders(Principal principal) {
        if (principal == null) {
            return ResponseEntity.ok(new ArrayList<>());
        }

        String username = principal.getName();
        log.info("Fetching orders for user: {}", username);

        // 通过创建者用户名查询订单
        List<Order> userOrders = orderRepository.findByCreatorUsername(username);
        log.info("Found {} orders for user {}", userOrders.size(), username);

        // 将Order实体转换为OrderDTO
        List<OrderDTO> orderDTOs = userOrders.stream()
                .map(order -> {
                    OrderDTO dto = new OrderDTO();
                    // 设置DTO属性...
                    dto.setId(order.getId());
                    dto.setOrderNumber(order.getOrderNumber());
                    dto.setShipperInfo(convertToAddressDTO(order.getShipperInfo()));
                    dto.setRecipientInfo(convertToAddressDTO(order.getRecipientInfo()));
                    dto.setItemDescription(order.getItemDescription());
                    dto.setWeight(order.getWeight());
                    dto.setCalculatedFee(order.getCalculatedFee());
                    dto.setStatus(order.getStatus());
                    dto.setCreationTime(order.getCreationTime());
                    dto.setPickupTime(order.getPickupTime());
                    dto.setDeliveryTime(order.getDeliveryTime());
                    dto.setDeliveryPersonId(order.getDeliveryPersonId());
                    return dto;
                })
                .collect(Collectors.toList());

        return ResponseEntity.ok(orderDTOs);
    }
    
    /**
     * 将Address实体转换为AddressDTO
     */
    private AddressDTO convertToAddressDTO(Address address) {
        if (address == null) {
            return null;
        }
        AddressDTO dto = new AddressDTO();
        dto.setName(address.getName());
        dto.setPhone(address.getPhone());
        dto.setProvince(address.getProvince());
        dto.setCity(address.getCity());
        dto.setDistrict(address.getDistrict());
        dto.setDetailAddress(address.getDetailAddress());
        dto.setLongitude(address.getLongitude());
        dto.setLatitude(address.getLatitude());
        return dto;
    }
    
    /**
     * 获取当前登录用户的最近一个订单
     */
    @GetMapping("/latest")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<OrderDTO> getLatestUserOrder(Principal principal) {
        if (principal == null) {
            return ResponseEntity.noContent().build();
        }

        String username = principal.getName();
        log.info("Fetching latest order for user: {}", username);

        // 通过创建者用户名查询订单并按创建时间降序排序
        List<Order> userOrders = orderRepository.findByCreatorUsernameOrderByCreationTimeDesc(username);
        
        if (userOrders.isEmpty()) {
            log.info("No orders found for user {}", username);
            return ResponseEntity.noContent().build();
        }
        
        // 获取最新的订单
        Order latestOrder = userOrders.get(0);
        log.info("Found latest order {} for user {}", latestOrder.getOrderNumber(), username);

        // 将Order实体转换为OrderDTO
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(latestOrder.getId());
        orderDTO.setOrderNumber(latestOrder.getOrderNumber());
        orderDTO.setShipperInfo(convertToAddressDTO(latestOrder.getShipperInfo()));
        orderDTO.setRecipientInfo(convertToAddressDTO(latestOrder.getRecipientInfo()));
        orderDTO.setItemDescription(latestOrder.getItemDescription());
        orderDTO.setWeight(latestOrder.getWeight());
        orderDTO.setCalculatedFee(latestOrder.getCalculatedFee());
        orderDTO.setStatus(latestOrder.getStatus());
        orderDTO.setCreationTime(latestOrder.getCreationTime());
        orderDTO.setPickupTime(latestOrder.getPickupTime());
        orderDTO.setDeliveryTime(latestOrder.getDeliveryTime());
        orderDTO.setDeliveryPersonId(latestOrder.getDeliveryPersonId());

        return ResponseEntity.ok(orderDTO);
    }
}